<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Db
 *
 * @author 耿鸿飞 <eoe2005@gmail.com>
 */
abstract class Db {
    public $_sortData = array();
    public $_insertid = 0;
    public $_affected_rows = 0;
    public $_rows = array();
    public $_var = array();
    public $_limit_start = false;
    public $_limit_len = false;
    
    public function getRow(String $sql){
        $this->limit(0, 1)->exec($sql);
        if(count($this->_rows) > 0){
            return $this->_rows[0];
        }
        return null;
    }
    public function getVar(String $sql){
        $row = $this->getRow($sql);
        if($row){
            foreach($row AS $v){
                return $v;
            }
        }
        return '';
    }
    public function getResults(String $sql){
        $this->query($sql);
        return $this->_rows;
    }
    public function insert(String $table,Array $data){
        $sql = sprintf("INSERT INTO %s(%s) VALUES('%s')",$table,  implode(',', array_keys($data)),  implode("','", array_values($data)));
        $this->query($sql);
        return $this->_insertid;
    }
    public function update(String $table,  Array $data,String $where = ""){
        $vs = array();
        foreach ($data AS $k=>$v){
            $vs[] = sprintf("%s='%s'",$k,$this->escape($v));
        }
        $sql = sprintf("UPDATE %s SET %s %s",$table,  implode(',', $vs),empty($where) ? "" : sprintf("WHERE %s",$where));
        if($this->query($sql)){
            return $this->_affected_rows;
        }
        return 0;
    }
    //
    public function _afterQuery(){
        $this->_sortData = array();
        $this->_limit_start = false;
    }
    public function _beforeQuery(){
        $this->_rows = array();
    }
    public function query(String $sql){
        $this->_beforeQuery();
        $this->exec($sql);
        Monk::app()->log->sql($sql);
        $this->_afterQuery();
    }
    public function limit(Int $start,Int $len){
        $this->_limit_start = $start;
        $this->_limit_len = $len;
        return $this;
    }
    
    public abstract function exec(String $sql);
    public abstract function escape(String $data);
    
    
}

?>
